package concurrecy;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class SerialNumberGenerator {
    private static volatile int count = 0;
    public static int generate() {
        return count ++;
    }
}

class CircularList {
    private final int size = 1 << 8;
    private final int[] elements = new int[size];
    private int index = 0;

    public synchronized void add(int value) {
        elements[index ++] = value;
        if(index >= size)
            index &= size - 1;
    }

    public synchronized boolean contains(int value) {
        for (int i = 0; i < size; i++) {
            if(elements[i] == value)
                return true;
        }
        return false;
    }
}


public class SerialNumberGeneratorDemo {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final CircularList list = new CircularList();
        for (int i = 0; i < 16; i++) {
            service.execute(() -> {
                while(true) {
                    int generate = SerialNumberGenerator.generate();
                    if (list.contains(generate))
                        new RuntimeException(generate + " existed!");
                    list.add(generate);
                    if(generate > 500000) {
                        System.out.println("exit");
                        System.exit(0);
                    }
                }
            });
        }
        service.shutdown();
    }
}
